﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Data;
using System.Reflection;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Timers;
using System.Windows.Controls.Primitives;

/*
 *  1. Размер папки.
    2. Горизонтальное разрешение.
    3. Пользовательский рейтинг фильма (1-5, если рейтинг не указывался, то =0).
    4. Наличие оригинальной звуковой дорожки (1 или 0 (+ или -?)).
    5. Наличие оригинальных титров (аналогично п.4).
    6. Качество озвучки (аналогично п.3).
    7. Качество изображения (аналогично п.3).
 * */

namespace ShumaDaf
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Setta mySettings;
        private delegate void OneArgDelegate(List<string> l);
        List<DataTabControl> dtclist = new List<DataTabControl>();

        public MainWindow()
        {
            InitializeComponent();
        }

        public static Version getAssemblyVersion()
        {
            Assembly assem = Assembly.GetEntryAssembly();
            AssemblyName assemName = assem.GetName();
            Version ver = assemName.Version;
            return ver;
        }

        public void ShowMessage(string msg)
        {
            logListBox.Items.Add(msg);
        }

        #region WindowEvents

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            savePosition();
            btnSave_Click(null, null);
        }



        private void detectForiegnXml()
        {
            string searchPath = Directory.GetCurrentDirectory();
            string[] files = Directory.GetFiles(searchPath, "collection-*.xml");
            foreach (string filename in files)
            {
                DataTabControl dc = new DataTabControl();

                dc.ForiegnXml = true;
                dc.PathToXmlFile = filename;
                if (this.Height > 130) dc.vis = this.Height - 130; else dc.vis = this.Height;
                dtclist.Add(dc);

                StackPanel dp = new StackPanel();
                dp.Children.Add(dc);

                Label l = new Label();
                l.Content = "This is foriegn XML data file, located near me. I display his content, don't edit them!";
                dp.Children.Add(l);


                TabItem ti = new TabItem();
                ti.Background = Brushes.Bisque;
                ti.Content = dp;
                ti.Header = "Foriegn " + System.IO.Path.GetFileName(filename);

                mainTabControl.Items.Add(ti);
            }
        }

        private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (e.NewSize.Height > 130)
                dg1.MaxHeight = e.NewSize.Height - 130;
            foreach (DataTabControl dt in dtclist)
                dt.vis = e.NewSize.Height - 130;

        }

        #endregion


        #region SaveColumnsPosition
        private void restoreColumnsFromSettings()
        {

            DataSet ds = mySettings.getSettings();
            if (ds == null) return;
            /// выполняем проверку исключения, чтобы избежать кривого файла настроек
            try
            {
                {
                    // Sorting 
                    DataView dataView = new DataView(ds.Tables["TableProperties"]);
                    dataView.Sort = "index DESC";
                    foreach (DataRowView r in dataView)
                    {
                        int n = (int)(r["n"]);
                        DataGridColumn c = dg1.Columns[n];
                        c.Width = (double)r["width"];
                        c.Visibility = (bool)r["visible"] ? System.Windows.Visibility.Visible : System.Windows.Visibility.Hidden;
                        c.DisplayIndex = (int)r["index"];
                    }
                }
            }
            catch (Exception)
            {
                mySettings.broken();
            }

        }
        private void savePosition()
        {
            try
            {
                mySettings.clearTableProp();
                for (int i = 0; i < dg1.Columns.Count; i++)
                {
                    DataGridColumn c = dg1.Columns[i];
                    mySettings.addTableProp(i, c.Width, c.Visibility, c.DisplayIndex, c.Header.ToString());
                }
                mySettings.writeSettings();
            }
            catch (Exception) { }
        }
        #endregion


        private void btnScan_Click(object sender, RoutedEventArgs e)
        {
            List<string> dirs = new List<string>();
            foreach (string s in scanListBox.Items)
            {
                if (!Directory.Exists(s))
                {
                    ShowMessage("Directory " + s + " is offline, skip it!");
                    continue;
                }
                else ShowMessage("Scan " + s);
                dirs.Add(s);
            }
            scanProgressBar.Visibility = Visibility.Visible;
            OneArgDelegate fetcher = new OneArgDelegate(MMovies.scanDirectory);
            fetcher.BeginInvoke(dirs, new AsyncCallback(scanDone), null);
            filterInput.Text = "";
            
        }


        private void scanDone(IAsyncResult r)
        {

            // управление надо отдать обратно в треду отрисовки, этот вызов асинхронный  и мы не имеем доступа у элементам интерфейса
            this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new NoArgDelegate(hideProgress));
        }

        private void hideProgress()
        {
            scanProgressBar.Visibility = Visibility.Collapsed;
            showCol();
            restoreSorting();

        }

        private void showCol()
        {
            // Отображение финальной коллекции
            XmlDataProvider pr = (XmlDataProvider)Resources["myXMLdata"];
            string d = Directory.GetCurrentDirectory();
            string p = System.IO.Path.Combine(d, MMovies.permanentCollectionPath);
            pr.Source = new Uri(p, UriKind.Absolute);
            pr.Refresh();

        }


        private void LocalTitle_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            DataGridCell cell = (DataGridCell)sender;
            DataGridRow r = Sherbanov.Helpers.WPFHelper.FindVisualParent<DataGridRow>(cell);
            XmlElement x = (XmlElement)r.Item;
            try
            {
                string imdb = x.SelectSingleNode("IMDB").FirstChild.Value;
                Process.Start("http://www.imdb.com/title/" + imdb + "/");
            }
            catch (Exception) { }
        }

        private void dataGridRow_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            DataGridCell cell = (DataGridCell)sender;

            string path = ((TextBlock)(cell.Content)).Text;
            if (Directory.Exists(path)) Process.Start("Explorer.exe", "\"" + path + "\"");

        }

        private void MediaInfo_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DataGridCell cell = (DataGridCell)sender;

            cell.IsEditing = !cell.IsEditing;
            e.Handled = true;

        }


        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            XmlDataProvider pr = (XmlDataProvider)Resources["myXMLdata"];
            XmlDocument doc = pr.Document;
            MMovies.saveXML(doc, this);

        }

        private void btnClearLog_Click(object sender, RoutedEventArgs e)
        {
            logListBox.Items.Clear();
        }



        #region DirectoryList
        private void btnAddNewPath_Click(object sender, RoutedEventArgs e)
        {
            scanListBox.Items.Add(newItemNextBox.Text);
        }

        //remove all selected
        private void Button_Click(object sender, RoutedEventArgs e)
        {

            int index;
            do
            {
                index = scanListBox.SelectedIndex;
                if (index != -1) scanListBox.Items.RemoveAt(index);
            } while (index != -1);
        }

        private void dirlistsaveButton_Click(object sender, RoutedEventArgs e)
        {
            StreamWriter tw = new StreamWriter("directory.list");
            foreach (string i in scanListBox.Items)
            {
                tw.WriteLine(i);
            }
            tw.Close();
        }

        private void loadDirlist()
        {
            StreamReader sr = null;
            try
            {
                sr = new StreamReader("directory.list");
                if (File.Exists("directory.list"))
                {
                    scanListBox.Items.Clear();
                    while (true)
                    {
                        string line = sr.ReadLine();
                        scanListBox.Items.Add(line);
                        if (sr.EndOfStream) break;
                    }
                    sr.Close();
                }
            }
            catch (Exception e)
            {
                ShowMessage("Errror load directorylist. List Cleared." + e.Message);
            }
            finally { try { sr.Close(); } catch { } }
        }

        #endregion



        DataGridColumn currentSortColumn = null;
        ListSortDirection? currentSortDirection = null;

        void GetSortInfo(DataGrid dg)
        {
            try
            {
                currentSortColumn = dg.Columns.Where(c => c.SortDirection.HasValue).Single();
                currentSortDirection = currentSortColumn.SortDirection.Value;
            }
            catch (Exception)
            {
                currentSortColumn = null;
            }
        }



        private void dg1_Sorting(object sender, DataGridSortingEventArgs e)
        {
            /* DataGridColumn column = e.Column;
             string path = "";
             string HandledPaths = "Size CollectionNumber RunningTime";
             if (column is DataGridTextColumn)
             {
                 path = getColumnName((DataGridTextColumn)e.Column);
                 if (HandledPaths.Contains(path))
                 {
                     e.Handled = true;
                     IComparer comparer = null;
                     ListSortDirection direction = (column.SortDirection != ListSortDirection.Ascending) ? ListSortDirection.Ascending : ListSortDirection.Descending;
                     //set the sort order on the column
                     column.SortDirection = direction;
                     column.GetLocalValueEnumerator();
                     ListCollectionView lcv = (ListCollectionView)CollectionViewSource.GetDefaultView(dg1.ItemsSource);
                     comparer = new IntsInStringComparer(direction, path);
                     lcv.CustomSort = comparer;
                 }
                 else
                     return;
             }*/
        }

        private void dg1_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
        {
            XmlElement x = (XmlElement)e.Row.Item;
            XmlNode modified = x.SelectSingleNode("Modified");
            if (modified == null)
            {
                modified = x.AppendChild(x.OwnerDocument.CreateElement("Modified"));
            }
        }

        private void dg1_Loaded(object sender, RoutedEventArgs e)
        {
        }

        #region Players
        private void runPlayer(string filename, Button b, bool fake)
        {
            if (File.Exists(filename))
            {
                StreamReader sr = new StreamReader(filename);
                string cmd = sr.ReadLine();
                string name = sr.ReadLine();
                sr.Close();
                if (name != null && name.Length > 0) b.Content = name;
                if (File.Exists(cmd))
                {
                    XmlElement x = (XmlElement)dg1.SelectedItem;

                    if (!fake & x != null)
                    {

                        string path = "\"" + x.SelectSingleNode("Path").FirstChild.Value + "\"";
                        Process.Start(cmd, path);
                    }
                }
                else
                {
                    ShowMessage("Omg! External exe in file " + filename + " " + cmd + " dos not exist :(");
                    b.IsEnabled = false;
                }
            }
            else
            {
                ShowMessage("Omg! External file " + filename + " dos not exist :(");
                b.IsEnabled = false;
            }
        }
        private void btnPlayer1_Click(object sender, RoutedEventArgs e)
        {
            runPlayer("Player1.txt", (Button)sender, false);
        }
        private void btnPlayer2_Click(object sender, RoutedEventArgs e)
        {
            runPlayer("Player2.txt", (Button)sender, false);
        }
        #endregion

        #region filter
        public bool Filter(object de)
        {
            XmlElement x = de as XmlElement;

            if (filterInput.Text.Length > 0)
            {
                try
                {
                    XmlNodeList actors = x.SelectNodes("Artists/Person/Name");
                    foreach (XmlNode a in actors)
                    {
                        if (a.FirstChild.Value.ToLower().Contains(filterInput.Text.ToLower()))
                            return true;
                    }

                    XmlNode t = x.SelectSingleNode("LocalTitle");
                    if (t.FirstChild.Value.ToLower().Contains(filterInput.Text.ToLower()))
                        return true;
                    XmlNode t2 = x.SelectSingleNode("OriginalTitle");
                    if (t.FirstChild.Value.ToLower().Contains(filterInput.Text.ToLower()))
                        return true;
                    return false;
                }
                catch (Exception) { return true; }
            }
            return (true);
        }

        Timer inputTimer;

        private void filterInput_TextChanged(object sender, TextChangedEventArgs e)
        {
            //btnFilter_Click(null, null);
            if (inputTimer == null)
            {
                inputTimer = new Timer(500);
                inputTimer.Elapsed += new ElapsedEventHandler(inputTimer_Elapsed);
                inputTimer.AutoReset = false;
            }
            inputTimer.Stop();
            inputTimer.Start();

        }

        private void filterEvent()
        {
            ListCollectionView lcv = (ListCollectionView)CollectionViewSource.GetDefaultView(dg1.ItemsSource);
            lcv.Filter = new Predicate<object>(Filter);

        }

        private delegate void NoArgDelegate();
        void inputTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            inputTimer.Stop();
            this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new NoArgDelegate(filterEvent));
        }
        #endregion






        #region ContextMenu
        private string RowMenuPath = null;
        private XmlElement RowMenuElement = null;
        private void eventDataGridRowMouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            string path = null;
            string name = null;
            XmlElement x = null;
            RowMenuPath = null;
            try
            {
                DataGridRow r = sender as DataGridRow;
                x = (XmlElement)r.Item;

                path = x.SelectSingleNode("Path").FirstChild.Value;
                name = x.SelectSingleNode("LocalTitle").FirstChild.Value;
            }
            catch (Exception) { return; }
            RowMenuPath = path;
            RowMenuElement = x;
            ContextMenu cxActions = new ContextMenu();

            MenuItem mi = new MenuItem();
            mi.Header = "Movie '" + name + "' is bullshit! Delete Folder forever!";
            mi.Click += new RoutedEventHandler(mi_Click);
            cxActions.Items.Add(mi);

            MenuItem mi2 = new MenuItem();
            mi2.Header = "Movie '" + name + "' mistake! Clear MyMovies metadata";
            mi2.Click += new RoutedEventHandler(mi2_Click);
            cxActions.Items.Add(mi2);

            MenuItem mi3 = new MenuItem();
            mi3.Header = "I delete this movie. it's not offline. It's Erased!";
            mi3.Click += new RoutedEventHandler(mi3_Click);
            cxActions.Items.Add(mi3);

            dg1.ContextMenu = cxActions;
            cxActions.IsOpen = true;
        }

        void mi3_Click(object sender, RoutedEventArgs e)
        {
            RowMenuElement.ParentNode.RemoveChild(RowMenuElement);
            XmlDataProvider pr = (XmlDataProvider)Resources["myXMLdata"];
            XmlDocument doc = pr.Document;
            MMovies.saveXML(doc, this);

        }

        // erase directory
        void mi_Click(object sender, RoutedEventArgs e)
        {
            if (Directory.Exists(RowMenuPath))
            {
                Directory.Delete(RowMenuPath, true);
            }
            mi3_Click(null, null);

        }

        //clear metadata
        void mi2_Click(object sender, RoutedEventArgs e)
        {
            if (Directory.Exists(RowMenuPath))
            {
                FileInfo[] files = new DirectoryInfo(RowMenuPath).GetFiles("Mymovies.xml", SearchOption.AllDirectories);
                foreach (FileInfo fi in files)
                {
                    fi.Delete();
                }
            }
        }
        #endregion

        #region checkboxSingleClick
        //
        // SINGLE CLICK EDITING
        //
        private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DataGridCell cell = sender as DataGridCell;
            if (cell != null && !cell.IsEditing && !cell.IsReadOnly)
            {
                if (!cell.IsFocused)
                {
                    cell.Focus();
                }
                DataGrid dataGrid = Sherbanov.Helpers.WPFHelper.FindVisualParent<DataGrid>(cell);
                if (dataGrid != null)
                {
                    if (dataGrid.SelectionUnit != DataGridSelectionUnit.FullRow)
                    {
                        if (!cell.IsSelected)
                            cell.IsSelected = true;
                    }
                    else
                    {
                        DataGridRow row = Sherbanov.Helpers.WPFHelper.FindVisualParent<DataGridRow>(cell);
                        if (row != null && !row.IsSelected)
                        {
                            XmlElement x = (XmlElement)row.Item;
                            XmlNode modified = x.SelectSingleNode("Modified");
                            if (modified == null)
                            {
                                modified = x.AppendChild(x.OwnerDocument.CreateElement("Modified"));
                            }
                        }
                    }
                }
            }
        }

 
        #endregion

        Queue<mySortedDescription> sortedQueue = null;
        /// <summary>
        /// Absolutly my own sorted logic
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dg1_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            ListCollectionView lcv = (ListCollectionView)CollectionViewSource.GetDefaultView(dg1.ItemsSource);
            if (lcv.IsEditingItem) return;

            if (Sherbanov.Helpers.WPFHelper.FindVisualParent<Thumb>((UIElement)e.OriginalSource) != null) return;
            DataGridColumnHeader header = Sherbanov.Helpers.WPFHelper.FindVisualParent<DataGridColumnHeader>((UIElement)e.OriginalSource);
            if (header == null) return;

            string path = Sherbanov.Helpers.WPFHelper.getColumnName(header.Column);
            if (sortedQueue == null) sortedQueue = new Queue<mySortedDescription>();

            mySortedDescription d = null;
            foreach (mySortedDescription my_d in sortedQueue)
            {
                // переключение уже имеющегося столбика
                if (my_d.column == header.Column)
                {
                    my_d.sortDescr.Direction = (my_d.sortDescr.Direction != ListSortDirection.Ascending) ? (ListSortDirection.Ascending) : (ListSortDirection.Descending);
                    d = my_d;
                    break;
                }
            }
            // сделаем D - по которому кликнули последним в очереди или первым в сортировке
            if (d != null)
            {
                Queue<mySortedDescription> tmp = new Queue<mySortedDescription>();
                foreach (mySortedDescription exist in sortedQueue)
                {
                    if (exist != d)
                        tmp.Enqueue(exist);
                }
                sortedQueue.Clear();
                foreach (mySortedDescription exist in tmp)
                {
                    sortedQueue.Enqueue(exist);
                }
                sortedQueue.Enqueue(d);
            }

            if (d == null)
            {
                d = new mySortedDescription();
                d.column = (DataGridColumn)header.Column;
                d.sortDescr = new SortDescription(path, ListSortDirection.Ascending);
                d.oldHeader = header.Column.Header.ToString();
                d.path = path;
                sortedQueue.Enqueue(d);
            }

            if (sortedQueue.Count > 2)
            {
                mySortedDescription del = sortedQueue.Dequeue();
                del.column.Header = del.oldHeader;
            }

            drawSoretedGrid(lcv);
        }

        private void restoreSorting()
        {
            drawSoretedGrid((ListCollectionView)CollectionViewSource.GetDefaultView(dg1.ItemsSource));
        }

        private void drawSoretedGrid(ListCollectionView lcv)
        {
            //show sorted

            int j = 0;
            if (sortedQueue == null) return;
            lcv.CustomSort = null;
            lcv.SortDescriptions.Clear();
            //find custom sorter
            string HandledPaths = "Size CollectionNumber RunningTime";
            foreach (mySortedDescription sort in sortedQueue)
            {
                if (HandledPaths.Contains(sort.path) && lcv.CustomSort == null)
                {
                    IComparer comparer = new IntsInStringComparer(sortedQueue);
                    lcv.CustomSort = comparer;
                    break;
                }
            }
            
            
            foreach (mySortedDescription sort in sortedQueue.Reverse())
            {
                j++;
                if (lcv.CustomSort == null)
                    lcv.SortDescriptions.Add(sort.sortDescr);
                if (sort.sortDescr.Direction == ListSortDirection.Ascending)
                    sort.column.Header = sort.oldHeader + ": v" + j;
                else
                    sort.column.Header = sort.oldHeader + ": ^" + j;
            }
            lcv.Refresh();
        }

        private void dg1_SourceUpdated(object sender, DataTransferEventArgs e)
        {

        }

        int tt = 0;
        private void dg1_TargetUpdated(object sender, DataTransferEventArgs e)
        {
            logListBox.Items.Add(++tt+"target updated " + DateTime.Now);
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            loadDirlist();
            mySettings = new Setta(this);

            btnScan_Click(null, null);
            //showCol();
            Version v = getAssemblyVersion();
            this.Title = "ShumaDaf build:" + v.ToString();

            runPlayer("Player1.txt", btnPlayer1, true); runPlayer("Player2.txt", btnPlayer2, true);

            detectForiegnXml();
            restoreColumnsFromSettings();

        }


    }


    #region  Comparer
    public class IntsInStringComparer : IComparer
    {

        private readonly Queue<mySortedDescription> queue;
        public IntsInStringComparer(Queue<mySortedDescription> queue)
        {
            this.queue = queue;
        }

        public int Compare(object x, object y)
        {
            try
            {
                XmlElement Node1 = (XmlElement)x;
                XmlElement Node2 = (XmlElement)y;


                int r=0;
                foreach (mySortedDescription descr in queue.Reverse())
                {
                    string path = descr.path;
                    ListSortDirection dir = descr.sortDescr.Direction;
                    string s1 = Node1.SelectSingleNode(path).FirstChild.Value;
                    string s2 = Node2.SelectSingleNode(path).FirstChild.Value;
                    string toIntPaths = "Size CollectionNumber RunningTime";
                    if (toIntPaths.Contains(path))
                    {
                        long v1 = System.Convert.ToInt64(s1);
                        long v2 = System.Convert.ToInt64(s2);
                        if (dir == ListSortDirection.Ascending)
                            r = v1.CompareTo(v2);
                        else
                            r = v2.CompareTo(v1);
                    }
                    else
                    {
                        if (dir == ListSortDirection.Ascending)
                            r = s1.CompareTo(s2);
                        else
                            r = s2.CompareTo(s1);
                    }
                    if (r != 0) break;
                }
                return r;
            }
            catch (Exception) { }
            return 0;
        }
    }
    #endregion

    #region Converters

    public class s2i : IValueConverter
    {

        public object Convert(object value, Type targetType,
                              object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null)
            {
                try
                {
                    int res = System.Convert.ToInt32(value);
                    return res;
                }
                catch (Exception e)
                {
                    return e.Message;
                }

            }
            return null;
        }

        public object ConvertBack(object value, Type targetType,
                                  object parameter, System.Globalization.CultureInfo culture)
        {
            return value.ToString();
        }
    }

    public class Int2ColorConverter : IValueConverter
    {
        public static readonly IValueConverter Instance = new Int2ColorConverter();
        public object Convert(object value, Type targetType,
                              object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null)
            {
                int priority = System.Convert.ToInt32(value);

                switch (priority)
                {
                    case 0: return Brushes.LightGray;
                    case 1: return Brushes.GreenYellow;
                    case 2: return Brushes.MediumVioletRed;
                    default: break;
                }
            }
            return null;
        }

        public object ConvertBack(object value, Type targetType,
                                  object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }
    }

    public class DesireConverter : IValueConverter
    {
        public static readonly IValueConverter Instance = new Int2ColorConverter();
        public object Convert(object value, Type targetType,
                              object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null)
            {
                int priority = (int)System.Convert.ToInt32(value);
                BrushConverter colorConverter = new BrushConverter();

                switch (priority)
                {
                    case 0: return Brushes.Gray;
                    case 1: return colorConverter.ConvertFromString("#FF008800") as Brush;
                    case 2: return colorConverter.ConvertFromString("#FF009900") as Brush;
                    case 3: return colorConverter.ConvertFromString("#FF00aa00") as Brush;
                    case 4: return colorConverter.ConvertFromString("#FF00CC00") as Brush;
                    case 5: return colorConverter.ConvertFromString("#FF00FF00") as Brush;

                    default: break;
                }
            }
            return null;
        }

        public object ConvertBack(object value, Type targetType,
                                  object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }
    }

    public class StatusColorConv : IValueConverter
    {
        public static readonly IValueConverter Instance = new Int2ColorConverter();
        public object Convert(object value, Type targetType,
                              object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null)
            {
                string status = (string)value;
                BrushConverter colorConverter = new BrushConverter();

                switch (status)
                {
                    case "online": return Brushes.PaleGreen;
                    case "offline": return Brushes.LightGray;
                    default: return Brushes.Gray;
                }
            }
            return null;
        }

        public object ConvertBack(object value, Type targetType,
                                  object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }
    }

    public class Int2CheckConverter : IValueConverter
    {

        public object Convert(object value, Type targetType,
                              object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null)
            {
                string status = (string)value;
                switch (status)
                {
                    case "0": return null;
                    case "1": return true;
                    case "2": return false;
                }
            }
            return null;
        }

        public object ConvertBack(object value, Type targetType,
                                  object parameter, System.Globalization.CultureInfo culture)
        {
            bool? state = (bool?)value;
            if (state == true) return "1";
            if (state == false) return "2";
            if (state == null) return "0";

            return "0";
        }
    }

    public class RuntimeConverter : IValueConverter
    {

        public object Convert(object value, Type targetType,
                              object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null)
            {
                int rt;
                string runtime = (string)value;
                try
                {
                    rt = System.Convert.ToInt32(runtime);
                }
                catch (Exception) { rt = 0; }
                if (rt == 0) return "?";
                int h = rt / 60;
                int m = rt % 60;
                return String.Format("{0:0}h:{1:00}m", h, m);
            }
            return null;
        }

        public object ConvertBack(object value, Type targetType,
                                  object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }
    }
    #endregion
}
